﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Leave;
using B.S.BasicData.Domain.Entities.Leave;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;

namespace B.S.BasicData.API.Write.Application.Handler.Leave
{
    /// <summary>
    /// 修改申请信息请求命令处理类
    /// </summary>
    public class UpdateLeaveHandler:IRequestHandler<UpdateLeaveCommand,ApiResult<int>>
    {
        IBaseRepository<LeaveApplicationModel> leaveRep;
        IMapper mapper;

        public UpdateLeaveHandler(IBaseRepository<LeaveApplicationModel> leaveRep, IMapper mapper)
        {
            this.leaveRep = leaveRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(UpdateLeaveCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var leave = leaveRep.GetAll().Where(x => x.Id == request.id).FirstOrDefault();
                if (leave==null)
                {
                    res.Msg = "申请信息不存在";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                if (request.state == LeaveStateEnum.已驳回&& (request.leaveReview==null|| request.leaveReview ==string.Empty))
                {
                    res.Msg = "审核原因必须进行填写";
                    res.Code = ApiEnum.Fail;
                    return Task.FromResult(res);
                }

                var model=mapper.Map(request,leave);

                leave.UpdateDate = DateTime.Now;
                leave.UpdateName = request.applicationName;

                int r=leaveRep.UpdateAsync(leave).Result;

                if (r > 0)
                {
                    res.Msg = "操作成功";
                    res.Code = ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "操作失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
